<?php


namespace App\Service\Admin;


use App\Constants\ContextKey;
use Hyperf\Utils\Context;
use App\Task\OperationLog\AdminTask;

class OperationLogService
{
    /**
     * 获取操作记录
     * @param $data
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function queryLog($data)
    {
        $result = di(AdminTask::class)->page($data['id'],[],[],$data['page']??1,$data['perPage']??15);
        $log = [];
        $arr = [];
        foreach ($result['data'] as $key=>$val){
            $arr[$key]['user_name'] = $val->user_name ?? '';
            $arr[$key]['event'] = !empty($val->event) ? $val->event : '';
            $arg = json_decode($val->arguments,true);
            $arr[$key]['arguments'] = $this->handleArg($arg);
            $arr[$key]['created_at'] = $val->created_at ?? '';
        }
        $log['data'] = array_values($arr);
        $log['total'] = $result['count'];
        $log['page'] = $result['page'];
        $log['per_page'] = $result['per_page'];
        return $log;
    }

    /**
     * 处理参数
     * @param array $data
     * @return string
     */
    public function handleArg(array $data)
    {
        $str = '';
        foreach ($data as $key=>$item){
            switch ($key){
                case 'post':
                    if (is_array($item)){
                        foreach ($item as $k=>$val){
                            $str .= '&'.$k.'='.$val;
                        }
                    }
                    break;
                case 'get':
                    if (is_array($item)){
                        foreach ($item as $k=>$v){
                            $str .= '&'.$k.'='.$v;
                        }
                    }
                    break;
                default:
                    $str .= '&'.$key.$item;
                    break;

            }
        }

        return $str;
    }

}